﻿using System;
using System.Globalization;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using FranceTriple.Dal;
using TeamFranceTriple.Config;
using System.Linq;
using System.Web.Security;

namespace TeamFranceTriple
{
    public partial class labaff : BasePage
    {
        private static String defaultCulture = TeamFranceTripleConfig.WebConfig.defaultculturewhenacceptcultureisnull.culture.ToLower();

        private HtmlLink newStyleSheet, newStyleSheet2;
        private HtmlMeta metaDescription, metaKeywords, metaAuthor, metaGenerator;

        private static String TsViewerFormat = @"http://cache.www.gametracker.com/components/html0/?host={0}&bgColor=000000&fontColor=ffffff&titleBgColor=000000&titleBgColor=000000&titleColor=FF9900&borderColor=555555&linkColor=FFCC00&borderLinkColor=000000&showMap=0&currentPlayersHeight=280&showCurrPlayers=1&showTopPlayers=0&showBlogs=0&width=160";
        private IFrameControl TSViewerIFrameControl;
        private Panel OneTeamPanel;

        private String ts3UrlFormat = "ts3server://{0}/?port={1}", ts3Target;
        private ListViewItem item;
        private Button btn, btn2;
        private Label FriendlyTeamMemberLabel, FriendlyTeamGuildmastersLabel;
        private HyperLink TeamspeakIpFriendlyTeamLink;
        private FranceTriple.Dal.FriendlyTeam ThisTeam = null;

        private Int32 FriendlyTeamId = 0;
        private Guid FriendlyMemberId;

        protected void Page_Load(object sender, EventArgs e)
        {
            // Si le visiteur est anonyme alors n'afficher que les teams publics
            if (!Page.User.Identity.IsAuthenticated)
            {
                FriendlyTeamEntityDataSource.WhereParameters.Add(new Parameter("IsPublicVisibleFriendlyTeam", System.Data.DbType.Boolean, "true"));
            }

            metaDescription = new HtmlMeta();
            metaDescription.Name = "DESCRIPTION";
            metaDescription.Content = "MetaDescriptionLaBaFF".ToLocalizedString().TextToHtml();
            Page.Header.Controls.Add(metaDescription);

            metaKeywords = new HtmlMeta();
            metaKeywords.Name = "KEYWORDS";
            metaKeywords.Content = "MetaKeywordsLaBaFF".ToLocalizedString().TextToHtml();
            Page.Header.Controls.Add(metaKeywords);

            metaAuthor = new HtmlMeta();
            metaAuthor.Name = "AUTHOR";
            metaAuthor.Content = "metaAuthor".ToLocalizedString().TextToHtml();
            Page.Header.Controls.Add(metaAuthor);

            metaGenerator = new HtmlMeta();
            metaGenerator.Name = "GENERATOR";
            metaGenerator.Content = "metaGenerator".ToLocalizedString().TextToHtml();
            Page.Header.Controls.Add(metaGenerator);

            // Ajouter la feuille de style commune
            newStyleSheet = new HtmlLink();
            newStyleSheet.Href = "~/Styles/Site.css";
            newStyleSheet.Attributes.Add("type", "text/css");
            newStyleSheet.Attributes.Add("rel", "stylesheet");
            Page.Header.Controls.Add(newStyleSheet);

            // Selectionner automatiquement une feuille de style sans fond d'écran pour les mobiles et avec pour les autres
            newStyleSheet2 = new HtmlLink();
            if (Request.Browser.IsMobileDevice)
            {
                newStyleSheet2.Href = "~/Styles/Site_Mobile.css";
            }
            else
            {
                newStyleSheet2.Href = "~/Styles/Site_Pc.css";
            }
            newStyleSheet2.Attributes.Add("type", "text/css");
            newStyleSheet2.Attributes.Add("rel", "stylesheet");
            Page.Header.Controls.Add(newStyleSheet2);
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {

        }

        protected void FriendlyTeamListView_DataBound(object sender, EventArgs e)
        {
            // Un chef de soirée peut ajouter une team à l'alliance.
            if (!User.IsInRole("RoleEveningChief"))
            {
                FriendlyTeamListView.InsertItem.Visible = false;
            }
        }

        protected void FriendlyTeamListView_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            item = e.Item;
            if (item.ItemType == ListViewItemType.DataItem)
            {
                ThisTeam = (FranceTriple.Dal.FriendlyTeam)item.DataItem;

                // Un Chef de soirée peut éditer et supprimer toutes les teams.
                // Un GuildMaster de cette team peut l'éditer
                if (User.IsInRole("RoleEveningChief") || (Page.User.Identity.IsAuthenticated && LaBaFFDal.GetTeamGuildMasterGuids(ThisTeam.Id).Contains(Guid.Parse(Membership.GetUser(false).ProviderUserKey.ToString()))))
                {
                    btn2 = item.FindControl("EditButton") as Button;
                    if (btn2 != null)
                        btn2.Visible = true;
                }

                if (User.IsInRole("RoleEveningChief"))
                {
                    btn = item.FindControl("DeleteButton") as Button;
                    if (btn != null)
                        btn.Visible = true;
                }

                FriendlyTeamMemberLabel = item.FindControl("FriendlyTeamMemberLabel") as Label;
                if (FriendlyTeamMemberLabel != null)
                {
                    FriendlyTeamMemberLabel.Text = String.Join(", ", LaBaFFDal.GetTeamMemberNames(ThisTeam.Id));
                }

                FriendlyTeamGuildmastersLabel = item.FindControl("FriendlyTeamGuildmastersLabel") as Label;
                if (FriendlyTeamGuildmastersLabel != null)
                {
                    FriendlyTeamGuildmastersLabel.Text = String.Join(", ", LaBaFFDal.GetTeamGuildMasterNames(ThisTeam.Id));
                }

                if (ThisTeam.TeamspeakIpFriendlyTeam != null && ThisTeam.TeamspeakIpFriendlyTeam != String.Empty)
                {
                    TeamspeakIpFriendlyTeamLink = item.FindControl("TeamspeakIpFriendlyTeamLink") as HyperLink;
                    if (TeamspeakIpFriendlyTeamLink != null)
                    {
                        try
                        {
                            ts3Target = String.Format(ts3UrlFormat,
                                ThisTeam.TeamspeakIpFriendlyTeam.Substring(0, ThisTeam.TeamspeakIpFriendlyTeam.LastIndexOf(":")),
                                ThisTeam.TeamspeakIpFriendlyTeam.Substring(ThisTeam.TeamspeakIpFriendlyTeam.LastIndexOf(":") + 1));
                        }
                        catch
                        {
                            //En cas de données ne contenant pas de ":" le champ est vide.
                            //Autrement l'affichage de la page entière se retrouve bloqué.
                            ts3Target = String.Empty;
                        }
                        TeamspeakIpFriendlyTeamLink.NavigateUrl = ts3Target;
                    }
                    //TSViewerIFrameControl = item.FindControl("TSViewerIFrameControl") as IFrameControl;
                    //if (TSViewerIFrameControl != null)
                    //{
                    //    TSViewerIFrameControl.Src = String.Format(TsViewerFormat, ThisTeam.TeamspeakIpFriendlyTeam);
                    //}
                }

                var TeamGameServerGridView = (GridView)item.FindControl("TeamGameServerGridView");

                if (TeamGameServerGridView != null)
                {
                    TeamGameServerGridView.DataSource = LaBaFFDal.GetGameServerByTeamByNicknameGame(ThisTeam.Id, "bf3");
                    TeamGameServerGridView.DataBind();
                }
            }
        }

        protected void FriendlyTeamListView_ItemEditing(object sender, ListViewEditEventArgs e)
        {
            // Identifier la team cible
            var IdLabel1 = (Label)FriendlyTeamListView.Items[e.NewEditIndex].FindControl("IdLabel1");

            if (IdLabel1 != null)
            {
                AddMemberObjectDataSource.SelectParameters["TeamId"].DefaultValue = IdLabel1.Text;
                RemoveMemberObjectDataSource.SelectParameters["TeamId"].DefaultValue = IdLabel1.Text;
                AddGuildMasterObjectDataSource.SelectParameters["TeamId"].DefaultValue = IdLabel1.Text;
                RemoveGuildMasterObjectDataSource.SelectParameters["TeamId"].DefaultValue = IdLabel1.Text;
            }
        }

        protected void FriendlyTeamListView_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            if (e.CommandName == "Edit")
            {
                this.Page.SetFocus("RemoveMemberPanel");
            }
        }

        protected void FriendlyTeamListView_ItemUpdating(object sender, ListViewUpdateEventArgs e)
        {
            if (!this.Page.IsValid)
            {
                e.Cancel = true;
                return;
            }
        }

        protected void FriendlyTeamListView_ItemInserting(object sender, ListViewInsertEventArgs e)
        {
            if (!this.Page.IsValid)
            {
                e.Cancel = true;
                return;
            }
        }

        protected void FriendlyTeamListView_ItemUpdated(object sender, ListViewUpdatedEventArgs e)
        {

        }

        protected void AddMemberGridView_SelectedIndexChanged(object sender, EventArgs e)
        {
            Label IdLabel1, FriendlyTeamMemberLabel;
            // Identifier la team cible
            IdLabel1 = (Label)FriendlyTeamListView.EditItem.FindControl("IdLabel1");
            if (IdLabel1 != null)
                FriendlyTeamId = Int32.Parse(IdLabel1.Text);

            var AddMemberGridView = (GridView)FriendlyTeamListView.EditItem.FindControl("AddMemberGridView");
            var RemoveMemberGridView = (GridView)FriendlyTeamListView.EditItem.FindControl("RemoveMemberGridView");

            //Identifier le membre et l'ajouter dans l'équipe
            FriendlyMemberId = Guid.Parse(AddMemberGridView.SelectedValue.ToString());
            if (FriendlyTeamId > 0)
                LaBaFFDal.AddMemberToFriendlyTeam(FriendlyTeamId, FriendlyMemberId);

            //Mettre à jour la liste des membres dans l'object en cours d'édition
            FriendlyTeamMemberLabel = FriendlyTeamListView.EditItem.FindControl("FriendlyTeamMemberLabel") as Label;
            if (FriendlyTeamMemberLabel != null)
            {
                FriendlyTeamMemberLabel.Text = String.Join(", ", LaBaFFDal.GetTeamMemberNames(FriendlyTeamId));
            }
            AddMemberGridView.DataBind();
            RemoveMemberGridView.DataBind();
            this.Page.SetFocus("RemoveMemberPanel");
        }

        protected void RemoveMemberGridView_SelectedIndexChanged(object sender, EventArgs e)
        {
            Label IdLabel1, FriendlyTeamMemberLabel;
            // Identifier la team cible
            IdLabel1 = (Label)FriendlyTeamListView.EditItem.FindControl("IdLabel1");
            if (IdLabel1 != null)
                FriendlyTeamId = Int32.Parse(IdLabel1.Text);

            var AddMemberGridView = (GridView)FriendlyTeamListView.EditItem.FindControl("AddMemberGridView");
            var RemoveMemberGridView = (GridView)FriendlyTeamListView.EditItem.FindControl("RemoveMemberGridView");

            //Identifier le membre et le retirer de l'équipe
            FriendlyMemberId = Guid.Parse(RemoveMemberGridView.SelectedValue.ToString());
            if (FriendlyTeamId > 0)
                LaBaFFDal.RemoveMemberFromFriendlyTeam(FriendlyTeamId, FriendlyMemberId);

            //Mettre à jour la liste des membres dans l'object en cours d'édition
            FriendlyTeamMemberLabel = FriendlyTeamListView.EditItem.FindControl("FriendlyTeamMemberLabel") as Label;
            if (FriendlyTeamMemberLabel != null)
            {
                FriendlyTeamMemberLabel.Text = String.Join(", ", LaBaFFDal.GetTeamMemberNames(FriendlyTeamId));
            }
            AddMemberGridView.DataBind();
            RemoveMemberGridView.DataBind();
            this.Page.SetFocus("RemoveMemberPanel");
        }

        protected void AddGuildMasterGridView_SelectedIndexChanged(object sender, EventArgs e)
        {
            Label IdLabel1, FriendlyTeamGuildmastersLabel;
            // Identifier la team cible
            IdLabel1 = (Label)FriendlyTeamListView.EditItem.FindControl("IdLabel1");
            if (IdLabel1 != null)
                FriendlyTeamId = Int32.Parse(IdLabel1.Text);

            var AddGuildMasterGridView = (GridView)FriendlyTeamListView.EditItem.FindControl("AddGuildMasterGridView");
            var RemoveGuildMasterGridView = (GridView)FriendlyTeamListView.EditItem.FindControl("RemoveGuildMasterGridView");

            //Identifier l'organisateur et l'ajouter dans l'équipe
            FriendlyMemberId = Guid.Parse(AddGuildMasterGridView.SelectedValue.ToString());
            if (FriendlyTeamId > 0)
                LaBaFFDal.AddGuildMasterToFriendlyTeam(FriendlyTeamId, FriendlyMemberId);

            //Mettre à jour la liste des guildmasters dans l'object en cours d'édition
            FriendlyTeamGuildmastersLabel = FriendlyTeamListView.EditItem.FindControl("FriendlyTeamGuildmastersLabel") as Label;
            if (FriendlyTeamGuildmastersLabel != null)
            {
                FriendlyTeamGuildmastersLabel.Text = String.Join(", ", LaBaFFDal.GetTeamGuildMasterNames(FriendlyTeamId));
            }

            AddGuildMasterGridView.DataBind();
            RemoveGuildMasterGridView.DataBind();
            this.Page.SetFocus("RemoveMemberPanel");
        }

        protected void RemoveGuildMasterGridView_SelectedIndexChanged(object sender, EventArgs e)
        {
            Label IdLabel1, FriendlyTeamGuildmastersLabel;
            // Identifier la team cible
            IdLabel1 = (Label)FriendlyTeamListView.EditItem.FindControl("IdLabel1");
            if (IdLabel1 != null)
                FriendlyTeamId = Int32.Parse(IdLabel1.Text);

            var AddGuildMasterGridView = (GridView)FriendlyTeamListView.EditItem.FindControl("AddGuildMasterGridView");
            var RemoveGuildMasterGridView = (GridView)FriendlyTeamListView.EditItem.FindControl("RemoveGuildMasterGridView");

            //Identifier l'organisateur et le retirer de l'équipe
            FriendlyMemberId = Guid.Parse(RemoveGuildMasterGridView.SelectedValue.ToString());
            if (FriendlyTeamId > 0)
                LaBaFFDal.RemoveGuildMasterFromFriendlyTeam(FriendlyTeamId, FriendlyMemberId);

            //Mettre à jour la liste des guildmasters dans l'object en cours d'édition
            FriendlyTeamGuildmastersLabel = FriendlyTeamListView.EditItem.FindControl("FriendlyTeamGuildmastersLabel") as Label;
            if (FriendlyTeamGuildmastersLabel != null)
            {
                FriendlyTeamGuildmastersLabel.Text = String.Join(", ", LaBaFFDal.GetTeamGuildMasterNames(FriendlyTeamId));
            }
            AddGuildMasterGridView.DataBind();
            RemoveGuildMasterGridView.DataBind();
            this.Page.SetFocus("RemoveMemberPanel");
        }
    }
}